package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 生成唯一id 使用redis
 * @author LENOVO
 * @Date 2022-11-30
 */
@Component
public class RedisIdWork {
    /**
     * 起始时间戳
     */
    private final static Long TIME_BEGIN=1670172386L;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public Long nextId(String keyPrefix){
        // 获取当前时间戳
        long end = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp = end - TIME_BEGIN;
        //获取当前日期 拼接key
        String dateFormat = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String key="incrm:"+dateFormat+":"+keyPrefix;

        //插入redis并获取返回的序号
        Long increment = stringRedisTemplate.opsForValue().increment(key);

        //拼接 生成 id
        return timestamp << 32 | increment;
    }
}
